//
//  Cookie.m
//  niminban
//
//  Created by zhouteng on 16/10/6.
//  Copyright © 2016年 zhouteng. All rights reserved.
//


#import "Cookie.h"

#import "URLS.h"
#define KEY_OF_COOKIE @"COOKIE"

@implementation Cookie

+(void)apply:(void (^)(NSString *))success failure:(void (^)(NSError * _Nonnull))failure{
    NSString *URLString = GET_COOKIE;
    NSLog(GET_COOKIE);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString *userAgent = [manager.requestSerializer  valueForHTTPHeaderField:@"User-Agent"];
    userAgent = [userAgent stringByAppendingPathComponent:@"HavfunClient-iOS"];
    [manager.requestSerializer setValue:userAgent forHTTPHeaderField:@"User-Agent"];
    
    NSLog(@"[User-Agent]%@",userAgent);
    
    [manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString* s = [[NSString alloc] initWithData: responseObject encoding:NSUTF8StringEncoding];
        
        NSHTTPURLResponse *respose = (NSHTTPURLResponse *)task.response;
        NSArray* cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:respose.allHeaderFields forURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/",HOST]]];
        
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        
        [userDefaults setObject:data forKey:KEY_OF_COOKIE];
        
        NSLog(@"[cookies]%@",cookies);
        NSLog(@"[success]%@",s);
        
        success(s);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"[error]%@",[error localizedDescription]);
        failure(error);
    }];
}

+(BOOL)exist:(NSArray *__autoreleasing _Nullable *)cookies{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSData *cookiesdata = [userDefaults objectForKey:KEY_OF_COOKIE];
    if([cookiesdata length]) {
        *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        return YES;
    }
    return NO;
}
@end
